package com.xiaoyg.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockUninterruptible {

    //定义一个runnable

    public static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        test02();

    }

    public static void test02() throws InterruptedException{
        Runnable runnable = ()->{
            String name = Thread.currentThread().getName();
            boolean b = false;
            try {
                 b = lock.tryLock(3, TimeUnit.SECONDS);
                if (b){
                    System.out.println(name + "获得锁" + "进入同步代码块");
                    Thread.sleep(888888);
                }else {
                    System.out.printf(name +"指定时间内没有获得锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(b){

                }

            }
        };

        Thread t1 = new Thread(runnable);
        t1.start();
        Thread.sleep(1000);

        Thread t2 = new Thread(runnable);
        t2.start();
//
//        System.out.println("停止线程前");
//        t2.interrupt();
//        System.out.println("停止线程后");

//        Thread.sleep(1000);
//
//        System.out.println(t1.getState());
//        System.out.println(t2.getState());
    }

    public void test01() throws InterruptedException{
        Runnable runnable = ()->{
            String name = Thread.currentThread().getName();
            try {
                lock.lock();

                System.out.println(name + "获得锁" + "进入同步代码块");
                Thread.sleep(888888);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.printf(name+ "释放锁");
            }
        };

        Thread t1 = new Thread(runnable);
        t1.start();
        Thread.sleep(1000);

        Thread t2 = new Thread(runnable);
        t2.start();

        System.out.println("停止线程前");
        t2.interrupt();
        System.out.println("停止线程后");

        Thread.sleep(1000);

        System.out.println(t1.getState());
        System.out.println(t2.getState());
    }

}
